<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="32%"
      :title="title + '门店'"
    >
      <el-form
        :model="storeInfo"
        :rules="rules"
        ref="supplierForm"
        label-width="0"
      >
        <el-form-item prop="storeName">
          <div style="display: flex">
            <p style="width: 90px; text-align: center; font-weight: bold">
              名称：
            </p>
            <el-input
              size="small"
              clearable
              v-model="storeInfo.storeName"
              placeholder="请输入"
            >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="openTimeArray">
          <div style="display: flex">
            <p style="width: 90px; text-align: center; font-weight: bold">
              时间：
            </p>
            <div style="height: 32px; width: 100%">
              <el-time-picker
                is-range
                arrow-control
                value-format="HH:mm"
                v-model="storeInfo.openTimeArray"
                range-separator=":"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
              >
              </el-time-picker>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="storeArea">
          <div style="display: flex; width: 100%">
            <p style="width: 87px; text-align: center; font-weight: bold">
              面积：
            </p>
            <el-input
              size="small"
              placeholder="请输入门店面积"
              v-model="storeInfo.storeArea"
            >
              <a slot="suffix">㎡</a>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="address">
          <div style="display: flex; align-items: center">
            <p style="width: 90px; text-align: right; font-weight: bold">
              门店地址：
            </p>
            <el-input
              placeholder="请打开地图选择门店地址"
              v-model="storeInfo.address"
              size="small"
              disabled
            >
              <template slot="append">
                <el-link @click="openEarth">
                  <i class="el-icon-position"></i>
                </el-link>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <div class="row-tow">
          <el-form-item prop="shopManagerId">
            <div style="display: flex">
              <p style="width: 63px; text-align: right; font-weight: bold">
                店长：
              </p>
              <div
                style="padding-left: 16px; display: flex; align-items: center"
              >
                <span class="over-text" v-if="storeInfo.storeManagerName">
                  {{ storeInfo.storeManagerName }}
                </span>
                <div style="display: inline">
                  <el-button
                    type="primary"
                    size="small"
                    @click="opDialogVisibleshopManagerId(2)"
                    style="width: 92px"
                    >选择店长</el-button
                  >
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            :style="{ opacity: storeInfo.storeManagerPhone ? 1 : 0 }"
          >
            <div
              style="
                display: flex;
                justify-content: flex-end;
                align-items: center;
                margin-right: 20px;
              "
            >
              <p style="width: 79px; text-align: center; font-weight: bold">
                店长电话：
              </p>
              {{ storeInfo.storeManagerPhone }}
            </div>
          </el-form-item>
        </div>
        <div class="row-tow">
          <el-form-item prop="franchiseeId">
            <div style="display: flex">
              <p style="width: 63px; text-align: right; font-weight: bold">
                加盟商：
              </p>
              <div
                style="padding-left: 16px; display: flex; align-items: center"
              >
                <span class="over-text" v-if="storeInfo.franchiseeName">
                  {{ storeInfo.franchiseeName }}</span
                >
                <div style="display: inline">
                  <el-button
                    type="primary"
                    size="small"
                    @click="opDialogVisibleshopManagerId(1)"
                    >选择加盟商</el-button
                  >
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            :style="{
              opacity: storeInfo.franchiseePhone ? 1 : 0,
              marginBottom: 0,
            }"
          >
            <div
              style="
                display: flex;
                justify-content: flex-end;
                align-items: center;
                margin-right: 20px;
              "
            >
              <p style="width: 130px; text-align: center; font-weight: bold">
                加盟商电话：
              </p>
              {{ storeInfo.franchiseePhone }}
            </div>
          </el-form-item>
        </div>
        <el-form-item prop="businessLicenseList">
          <div style="display: flex">
            <p style="width: 73px; text-align: center; font-weight: bold">
              营业执照：
            </p>
            <!-- <rayUpload @url="getImageUrl"></rayUpload> -->
            <Uploader
              @change="imgChange($event, 1)"
              :limit="1"
              :value="storeInfo.businessLicenseList"
            ></Uploader>
          </div>
        </el-form-item>
        <el-form-item prop="productionLicenseList">
          <div style="display: flex">
            <p style="width: 73px; text-align: center; font-weight: bold">
              经营许可：
            </p>
            <!-- <rayUpload @url="getImageUrl"></rayUpload> -->
            <Uploader
              @change="imgChange($event, 2)"
              :limit="1"
              :value="storeInfo.productionLicenseList"
            ></Uploader>
          </div>
        </el-form-item>
        <el-form-item prop="shopImageList">
          <div style="display: flex">
            <p style="width: 73px; text-align: center; font-weight: bold">
              门店实拍：
            </p>
            <!-- <rayUpload @url="getImageUrl"></rayUpload> -->
            <Uploader
              @change="imgChange($event, 3)"
              :limit="6"
              :value="storeInfo.shopImageList"
            ></Uploader>
          </div>
        </el-form-item>
        <div style="margin-top: 20px; text-align: center">
          <el-button
            @click="dialogVisible = false"
            style="
              background-color: #f3f6fd;
              color: #303e9d;
              width: 100px;
              height: 40px;
              font-weight: bold;
              font-size: 14px;
            "
            size="small"
            >取 消
          </el-button>
          <el-button
            @click="_submit"
            style="
              background-color: #303e9d;
              color: #eeeeee;
              width: 100px;
              height: 40px;
              font-weight: bold;
              font-size: 14px;
            "
            size="small"
            >保 存
          </el-button>
        </div>
      </el-form>
      <!--      <span slot="footer">-->
      <!--        <el-button @click="dialogVisible=false">取 消</el-button>-->
      <!--        <el-button style="background-color:#303e9d;color: #eeeeee" @click="_submit">确 定</el-button>-->
      <!--      </span>-->
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisibleshopManagerId"
      width="40%"
      :title="`选择${selectDiolTitle}`"
    >
      <el-form label-width="0">
        <el-form-item prop="goodsId">
          <div style="display: flex; align-items: center">
            <div style="width: 80%; margin-right: 20px">
              <el-input
                size="small"
                clearable
                v-model="selectUserPhone"
                placeholder="请输入手机号码"
              >
              </el-input>
            </div>

            <el-button
              type="primary"
              size="small"
              style="height: 32px"
              @click="selectUser"
              >查询</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <el-table
        v-if="userData.length"
        :data="userData"
        height="250px"
        border
        stripe
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{
          fontSize: '14px',
          'background-color': '#F3F6FD',
          color: '#333333',
          textAlign: 'center',
        }"
      >
        <el-table-column prop="userName" label="昵称"></el-table-column>
        <el-table-column prop="phoneNum" label="电话"></el-table-column>
        <el-table-column prop="createTime" label="注册时间"></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
            <el-button
              type="primary"
              size="mini"
              style="height: 32px"
              @click="selectUserCheck(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <init-map ref="initMapD" @addStatus="receiveMessage"></init-map>
  </div>
</template>

<script>
import initMap from '../initMap.vue'
// const Uploader1 = () => import('@/components/Element/Uploader.vue')
// const Uploader2 = () => import('@/components/Element/Uploader.vue')
// import rayUpload from '@/RayComponents/rayUpload.vue'
import Uploader from '@/components/Element/Uploader.vue'
export default {
  name: 'dialogGoods',
  components: { Uploader, initMap },
  data() {
    return {
      dialogVisible: false,
      selectDiolTitle: '',
      title: '',
      userName: '',
      phoneNum: '',
      baking: [],

      userData: [],
      selectUserPhone: '',
      dialogVisibleshopManagerId: false,
      storeInfo: {
        // goodsId: null,
        storeName: '',
        address: '',
        lat: '', // 门店纬度
        lon: '', // 门店经度
        openTimeArray: '',
        openTime: '', //营业时间段
        shopImageList: [], //门店实拍图
        businessLicense: '', //营业执照
        businessLicenseList: [],
        productionLicense: '', //生产许可证
        productionLicenseList: [],
        shopManagerId: null, //店长id
        storeManagerName: '',
        storeManagerPhone: '',

        franchiseeId: null, //加盟商ID
        franchiseeName: '',
        franchiseePhone: '',
      },
      brandList: [],
      recordInfo: {},
      recordId: '',
      storeId: '',
      supplierList: [],
      rules: {
        storeName: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' },
        ],
        storeArea: [
          { required: true, message: '请输入门店面积', trigger: 'blur' },
        ],
        openTimeArray: [
          { required: true, message: '请选择营业时间', trigger: 'change' },
        ],
        address: [{ required: true, message: '请选择地址', trigger: 'change' }],
        // spec: [{ required: true, message: '请输入规格', trigger: 'blur' }],
        shopImageList: [
          { required: true, message: '请上实拍图', trigger: 'change' },
        ],
        // storeType: [
        //   { required: true, message: '请选择门店类型', trigger: 'change' },
        // ],
        // storePhone: [
        //   { required: true, message: '请输入门店电话', trigger: 'blur' },
        //   {
        //     pattern: /^1[3-9]\d{9}$/,
        //     message: '请输入有效的手机号码',
        //     trigger: 'blur',
        //   },
        // ],
        // franchiseeId: [
        //   { required: true, message: '请选择加盟商', trigger: 'change' },
        // ],
        // brandPartyId: [
        //   { required: true, message: '请选择品牌方', trigger: 'change' },
        // ],
        // storeArea: [
        //   { required: true, message: '请输入门店面积', trigger: 'blur' },
        //   {
        //     validator(rule, value, callback) {
        //       const num = parseFloat(value)
        //       if (!/^\d+(\.\d{1,2})?$/.test(value)) {
        //         return callback(new Error('请输入合法的正数（最多两位小数）'))
        //       }
        //       if (num <= 0) {
        //         return callback(new Error('面积必须大于 0'))
        //       }
        //       callback()
        //     },
        //     trigger: 'blur',
        //   },
        // ],
      },
    }
  },
  mounted() {
    // this.getCategoryList()
  },
  methods: {
    selectUser() {
      if (!this.selectUserPhone) {
        return this.$message.warning('请输入手机号')
      }
      this.$api
        .userGetUserVo({
          phoneNum: this.selectUserPhone,
          pageSize: 100,
          pageNumber: 1,
        })
        .then((res) => {
          console.log('查询的用户', res)
          if (res.data) {
            this.userData = res.data
          }
        })
    },
    selectUserCheck(val) {
      if (this.selectDiolTitle == '加盟商') {
        this.storeInfo.franchiseeId = val.userId
        this.storeInfo.franchiseeName = val.userName
        this.storeInfo.franchiseePhone = val.phoneNum
      } else if (this.selectDiolTitle == '店长') {
        this.storeInfo.shopManagerId = val.userId
        this.storeInfo.storeManagerName = val.userName
        this.storeInfo.storeManagerPhone = val.phoneNum
      }
      this.dialogVisibleshopManagerId = false
    },
    opDialogVisibleshopManagerId(type) {
      if (type === 1) {
        this.selectDiolTitle = '加盟商'
      } else if (type === 2) {
        this.selectDiolTitle = '店长'
      }
      this.userData = []
      this.selectUserPhone = ''
      this.dialogVisibleshopManagerId = true
    },

    openEarth() {
      this.$refs.initMapD.handleOpen()
    },
    getCategoryList() {
      this.$api.bakingGetCategoryList().then((res) => {
        console.log('获取商品分类', res)
        const finallyDataList = res
        if (finallyDataList.length) {
          finallyDataList.forEach((item) => {
            item.label = item.categoryName
            item.value = item.categoryId
            if (item.bakingList.length) {
              item.bakingList.forEach((sitem) => {
                sitem.label = sitem.bakingName
                sitem.value = sitem.bakingId
              })
            }
          })
        }
        this.baking = finallyDataList
      })
    },
    imgChange(e, type) {
      console.log('上传图片数组', e, type, this.storeInfo)
      // this.storeInfo.goodsImgArray = e
      if (type === 1) {
        //  营业执照
        if (!e.length) {
          this.storeInfo.businessLicense = ''
        }
        this.storeInfo.businessLicenseList = e
      } else if (type === 2) {
        //  经营许可
        if (!e.length) {
          this.storeInfo.productionLicense = ''
        }
        this.storeInfo.productionLicenseList = [...e]
      } else if (type === 3) {
        // 门店实拍
        this.storeInfo.shopImageList = []
        this.storeInfo.shopImageList = [...e]
      }
    },
    getImageUrl(e) {
      console.log('上传完毕', e)
    },
    handleOpen(val) {
      console.log('addGoods2', val)
      this.dialogVisible = true
      if (val) {
        this.title = '编辑'
        Object.keys(this.storeInfo).forEach((key) => {
          if (val.hasOwnProperty(key)) {
            this.storeInfo[key] = val[key]
          }
        })
        if (val.image) {
          this.storeInfo.goodsImgArray = [val.image]
          this.storeInfo.goodsImg = val.image
        }
        this.storeInfo.bakingIdSelect = [val.categoryId, val.bakingId]
        console.log('this.storeInfo.', this.storeInfo)
      } else {
        this.title = '录入'
        this.storeInfo = this.$options.data.call(this).storeInfo
        this.$nextTick(() => {
          this.$refs.supplierForm?.clearValidate?.() // 清除校验状态
        })
      }
    },

    receiveMessage(data) {
      this.storeInfo.address = data.address
      this.storeInfo.lat = data.latitude
      this.storeInfo.lon = data.longitude
    },

    async _submit() {
      this.$refs.supplierForm.validate(async (valid) => {
        if (!valid) return false
        try {
          if (this.storeInfo.openTimeArray.length) {
            this.storeInfo.openTime = `${this.storeInfo.openTimeArray[0]}-${this.storeInfo.openTimeArray[1]}`
          }
          if (!this.storeInfo.shopManagerId) {
            return this.$message.error('请选择店长!')
          }
          if (!this.storeInfo.franchiseeId) {
            return this.$message.error('请选择加盟商!')
          }
          if (!this.storeInfo.businessLicenseList.length) {
            return this.$message.error('请上传营业执照!')
          } else {
            this.storeInfo.businessLicense =
              this.storeInfo.businessLicenseList[0]
          }
          if (!this.storeInfo.productionLicenseList.length) {
            return this.$message.error('请上传生产许可证!')
          } else {
            this.storeInfo.productionLicense =
              this.storeInfo.productionLicenseList[0]
          }
          console.log('最终', this.storeInfo)

          const apiMap = {
            录入: this.$api.shopAdd,
            编辑: this.$api.goodsUpdateGoods,
          }
          const apiFunc = apiMap[this.title]
          if (!apiFunc) return
          const resDate = await apiFunc(this.storeInfo)
          console.log('结果新增', resDate)
          if (resDate == 1) {
            this.$message.success(`${this.title}成功！`)
            this.dialogVisible = false
            this.$emit('addStatus', 1)
          }
        } catch (err) {
          console.error('接口请求出错：', err)
          this.$message.error('操作失败，请稍后重试')
        }
      })
    },
  },
}
</script>
<style scoped>
/deep/.img-item {
  width: 60px !important;
  height: 60px !important;
}
/deep/.el-date-editor--timerange {
  height: 100% !important;
  width: 100% !important;
}
/* /deep/.el-date-editor--timerange.el-input__inner {
  width: 100%;
} */
/deep/.el-range-separator {
  line-height: 23px !important;
}
/deep/.el-date-editor .el-range__icon {
  line-height: 27px !important;
}
/deep/.el-upload--picture-card {
  width: 60px !important;
  height: 60px !important;
}
/deep/.img-wrap .close {
  top: -10px !important;
  font-size: 20px !important;
}
.row-tow {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 0;
  /* display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row; */
}

::v-deep .el-input__inner {
  border-top-left-radius: 0 !important;
  border-bottom-left-radius: 0 !important;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .el-dialog {
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

/deep/ .el-dialog__header {
  background-color: #303e9d;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  /*border-top-left-radius: 20 px;*/
  /*/ / border-top-right-radius: 20 px;*/
}

.over-text {
  width: 120px;
  display: inline-block;
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>
